import 'dart:convert';
import 'dart:io';

import 'package:configure/configure.dart';
import 'package:flutter/material.dart';
import 'package:one_key_edit_ip/add_page.dart';
import 'package:one_key_edit_ip/ip_config.dart';

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<IpConfig> _list = [];

  @override
  void initState() {
    Configure.instance.then((value) {
      var val = value.getString("IpConfig");
      try {
        var list = json.decode(val) as List;
        setState(() {
          _list = list.map((e) => IpConfig.fromMap(e)).toList();
        });
      } catch (e) {
        print(e.toString());
      }
    });
    super.initState();
  }

  void _add(BuildContext context) {
    Navigator.of(context).push(MaterialPageRoute(builder: (context) {
      return AddPage();
    })).then((value) {
      if (null != value) {
        setState(() {
          _list.add(value);
        });
        Configure.instance.then((value) {
          value.setString("IpConfig", json.encode(_list.map((e) => e.toMap()).toList()));
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("一键修改IP"),
      ),
      body: Center(
        child: 0 == _list.length
            ? InkWell(
                onTap: () => _add(context),
                child: Padding(
                  padding: const EdgeInsets.all(16),
                  child: Text("无数据，点击添加IP"),
                ),
              )
            : ListView.builder(
                padding: EdgeInsets.symmetric(vertical: 8),
                itemCount: _list.length,
                itemBuilder: (context, index) {
                  var item = _list[index];
                  return Material(
                    color: Colors.white,
                    child: InkWell(
                      onTap: () => _onClick(context, item),
                      child: Container(
                        height: 60,
                        padding: EdgeInsets.symmetric(horizontal: 16),
                        decoration: BoxDecoration(
                          border: Border(
                            top: BorderSide(color: Theme.of(context).dividerColor),
                          ),
                        ),
                        child: Row(
                          children: [
                            Expanded(
                              child: Text(
                                item.name,
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                                style: TextStyle(
                                  fontSize: 16,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                            ),
                            IconButton(
                              onPressed: () => _onEdit(context, item),
                              icon: Icon(
                                Icons.edit,
                                color: Colors.blue,
                              ),
                            ),
                            IconButton(
                              onPressed: () => _onDelete(context, item),
                              icon: Icon(
                                Icons.delete_forever_outlined,
                                color: Colors.orange,
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  );
                },
              ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () => _add(context),
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }

  _onDelete(BuildContext context, IpConfig item) {
    showModalBottomSheet(
      context: context,
      builder: (context) {
        return Container(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Padding(
                padding: const EdgeInsets.all(16),
                child: Text(
                  '确认删除"${item.name}"?',
                  style: TextStyle(
                    fontSize: 16,
                  ),
                ),
              ),
              Row(
                children: [
                  Expanded(
                    child: FlatButton(
                      height: 46,
                      onPressed: () {
                        Navigator.of(context).pop(false);
                      },
                      child: Text(
                        "取消",
                        style: TextStyle(
                          color: Theme.of(context).primaryColor,
                        ),
                      ),
                    ),
                  ),
                  Expanded(
                    child: FlatButton(
                      height: 46,
                      color: Theme.of(context).primaryColor,
                      onPressed: () {
                        Navigator.of(context).pop(true);
                      },
                      child: Text(
                        "删除",
                        style: TextStyle(
                          color: Colors.white,
                        ),
                      ),
                    ),
                  ),
                ],
              )
            ],
          ),
        );
      },
    ).then((value) {
      if (true == value) {
        setState(() {
          _list.remove(item);
        });
        Configure.instance.then((value) {
          value.setString("IpConfig", json.encode(_list.map((e) => e.toMap()).toList()));
        });
        Scaffold.of(context).showSnackBar(
          SnackBar(
            content: Text(
              "删除成功",
              style: Theme.of(context).textTheme.bodyText1.copyWith(color: Colors.white),
            ),
          ),
        );
      }
    });
  }

  _onClick(BuildContext context, IpConfig item) {
    if (Platform.isWindows) {
      Future.wait([
        Process.run(
          "netsh",
          [
            "interface",
            "ip",
            "set",
            "address",
            item.macName,
            "static",
            item.ip,
            item.mask,
            item.gateway,
          ],
        ),
        Process.run(
          "netsh",
          [
            "interface",
            "ip",
            "set",
            "dns",
            item.macName,
            "static",
            item.defaultDns,
            if (item.spareDns?.isNotEmpty ?? false) item.spareDns,
          ],
        )
      ]).then((value) {
        Scaffold.of(context).showSnackBar(
          SnackBar(
            content: Text(
              "设置成功",
              style: Theme.of(context).textTheme.bodyText1.copyWith(color: Colors.white),
            ),
          ),
        );
      }, onError: (e) {
        Scaffold.of(context).showSnackBar(
          SnackBar(
            content: Text(
              "设置失败",
              style: Theme.of(context).textTheme.bodyText1.copyWith(color: Colors.red),
            ),
          ),
        );
      });
    } else if (Platform.isLinux) {
    } else if (Platform.isMacOS) {}
  }

  _onEdit(BuildContext context, IpConfig item) {
    Navigator.of(context).push(MaterialPageRoute(builder: (context) {
      return AddPage(config: item);
    })).then((value) {
      if (null != value) {
        setState(() {});
        Configure.instance.then((value) {
          value.setString("IpConfig", json.encode(_list.map((e) => e.toMap()).toList()));
        });
        Scaffold.of(context).showSnackBar(
          SnackBar(
            content: Text(
              "修改成功",
              style: Theme.of(context).textTheme.bodyText1.copyWith(color: Colors.white),
            ),
          ),
        );
      }
    });
  }
}
